<?php
namespace app\store\model\project;

use app\common\model\BaseModel;
use app\common\model\User;

class SeeDocker extends BaseModel{
    protected $autoWriteTimestamp = true;

    /**
     * 设置查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param): array
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($param, [
            'userId' => 0,          // 会员ID
            'search' => '',         // 搜索内容
            'betweenTime' => [],    // 起止时间
        ]);
        // 检索查询条件
        $filter = [];
        // 搜索内容: 用户昵称
        !empty($params['search']) && $filter[] = ['mobile', 'like', "%{$param['search']}%"];
        // 起止时间
        if (!empty($params['betweenTime'])) {
            $times = between_time($params['betweenTime']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    // 关联疾病类型
    public function illness(){
        return $this->hasOne(Illness::class,'id','type_illness')
            ->bind(['tag']);
    }

    // 关联用户信息
    public function user(){
        return $this->hasOne(User::class,'user_id','user_id')
            ->with('avatar')
            ->bind(['nick_name','avatar_url']);
    }

    // 获取列表数据
    public function getListArr(array $params)
    {
        $line = $params['line'] ?? 15;
        $filter = $this->getFilter($params);
        return $this->where(['is_delete' => 0])
            ->where($filter)
            ->with(['illness','user'])
            ->order('create_time', 'desc')
            ->paginate($line);
    }

    // 详情
    public static function detail(int $id)
    {
        $r = self::where(['id' => $id, 'is_delete' => 0])
            ->with('illness')
            ->find();
        $wherein = "{$r['province']},{$r['city']},{$r['area']}";
        $res = (new Region)->whereIn('name', $wherein)->select();
        $r['address'] = [$res[0]['id'], $res[1]['id'], $res[2]['id']];
        return $r;
    }

    // 修改
    public static function edit(array $data){
        $wherein = implode(',',$data['address']);
        $cityR = (new Region)->whereIn('id',$wherein)->select();
        return self::update([
            'name' => $data['name'],
            'mobile' => $data['mobile'],
            'remark' => $data['remark'],
            'type_illness' => $data['type_illness'],

            'province' => $cityR[0]['name'],
            'city' => $cityR[1]['name'],
            'area' => $cityR[2]['name'],
        ],['id'=>$data['id']]);
    }
}
